/***************************************************************************
 *   oboe.utils.ObjectParser						   *
 *   Copyright (C) 2011 by Felipe Manga					*
 *   lufeboma@gmail.com							*
 *									 *
 *   Permission is hereby granted, free of charge, to any person obtaining *
 *   a copy of this software and associated documentation files (the	   *
 *   "Software"), to deal in the Software without restriction, including   *
 *   without limitation the rights to use, copy, modify, merge, publish,   *
 *   distribute, sublicense, and/or sell copies of the Software, and to	*
 *   permit persons to whom the Software is furnished to do so, subject to *
 *   the following conditions:						 *
 *									 *
 *   The above copyright notice and this permission notice shall be	*
 *   included in all copies or substantial portions of the Software.	   *
 *									 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,	   *
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF	*
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR	 *
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
 *   OTHER DEALINGS IN THE SOFTWARE.					   *
 ***************************************************************************/

package oboe.utils;

import flash.utils.describeType;
import flash.utils.getDefinitionByName;

import flash.Vector;

class ObjectParser
{
public function new( d:Object ):Void
{
	var xml:XML = describeType( this );
	
	for( var key:String in d )
	{
	if( this.hasOwnProperty(key) )
	{
		var typeName:String = xml..variable.(@name==key).@type;
		var shortTypeName:String = typeName;
		var type:Class;
		var def:Class;
		var val:Object;
		if( typeName.substr(0, 21) == "__AS3__.vec::Vector<" ) 
		{
		shortTypeName = "Vector.<>";
		type = Class( getDefinitionByName( typeName.substr(21, typeName.length-22) ) );
		}
		
		switch( shortTypeName )
		{
		case "Vector<>":
		def = Class( getDefinitionByName(typeName) );
		var v:Dynamic = new def();
		this[key] = v;
		for each( val in d[key] )
		{
			v.push( new type(val) );
		}
		break;
		case "Array":
		type = this["get"+key+"Type"]();
		var a:Array = this[key] = new Array();
		for each( val in d[key] )
		{
			a.push( new type(val) );
		}
		break;
		case "String":
		case "int":
		case "uint":
		case "Number":
		this[key] = d[key];
		break;
		case "Boolean":
		val = d[key];
		if( val is String )
		{
			if( val=="true" ) this[key] = true;
			else this[key] = parseInt( String( val ) );
		}
		else
		{
			this[key] = val!=0;
		}
		break;
		default:
		def = Class(getDefinitionByName( typeName ));
		this[key] = new def( d[key] );
		}
	}
	}
}
}